<template>
  <PageListContainer>
    <div class="base-block">
      <k-search :model="state.params" @search="methods.onSearch" @reset="methods.onReset">
        <el-form-item label="手机号">
          <el-input v-model="state.params.mobile" clearable placeholder="请输入订单手机号"></el-input>
        </el-form-item>
        <el-form-item label="购买类型">
          <el-input v-model="state.params.subject" clearable placeholder="请输入购买类型"></el-input>
        </el-form-item>
        <el-form-item label="付款方式">
          <el-select v-model="state.params.pay_type" style="width: 180px">
            <el-option v-for="(o, i) in payTypeOptions" :key="i" :value="o.value" :label="o.label" />
          </el-select>
        </el-form-item>
        <el-form-item label="订单状态">
          <el-select v-model="state.params.trade_status" style="width: 180px">
            <el-option v-for="(o, i) in orderTypeOptions" :key="i" :value="o.value" :label="o.label" />
          </el-select>
        </el-form-item>
        <el-form-item label="1级渠道">
          <el-input v-model="state.params.utm_source" clearable placeholder="请输入1级渠道"></el-input>
        </el-form-item>
        <el-form-item label="2级渠道">
          <el-input v-model="state.params.utm_term" clearable placeholder="请输入2级渠道"></el-input>
        </el-form-item>
        <el-form-item label="订单时间">
          <el-date-picker
            v-model="state.params._dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="methods.onSearch"
          />
        </el-form-item>

        <el-form-item label="测试订单">
          <el-select v-model="state.params.has_test_order" style="width: 180px">
            <el-option v-for="(o, i) in hasTestOrderOptions" :key="i" :value="o.value" :label="o.label" />
          </el-select>
        </el-form-item>
      </k-search>
    </div>
    <div class="base-block">
      <KToolbar>
        <el-button type="primary" @click="handleOpenDrawer()">创建订单</el-button>
        <template #right>
          <div class="tool-right">
            <p class="right-desc">
              总计订单数<span>{{ totalOrders }}</span>
            </p>
            <p class="right-desc">
              订单金额<span>{{ orderAmounts }}</span>
            </p>
          </div>
        </template>
      </KToolbar>

      <KTable v-bind="tableState" v-on="tableEvent">
        <template #pay_type="{ row }">{{ row.pay_type == 8 ? `花呗${ row.tokio_instalment || 0 }期` : payTypeMap[row.pay_type] }}</template>
        <template #actions="{ row }">
          <el-link type="primary" :disabled="row.pay_type!=4" @click="onClickEdit(row)">编辑</el-link>
          <el-link :type="Number(row.trade_status) !== -300 ? 'danger' : undefined" :disabled="Number(row.trade_status) === -300" @click="handleRefund(row)">退款</el-link>
        </template>
      </KTable>
    </div>
    <EditDrawer ref="drawerRef" @after-submit="onAfterSubmit" />
  </PageListContainer>
</template>

<script setup lang="ts">
import { ref, computed, h } from 'vue';
import EditDrawer from './components/edit-drawer.vue';
import { ElMessage } from 'element-plus';
import { orderTypeOptions, hasTestOrderOptions, payTypeOptions, useTableList, payTypeMap } from './hooks/use-table';
import { AuthCode, hasPermission } from '@/modules/auth';
import { baseConfirm } from '@crud/index';
import { refundOrder, getList } from '@/api/crm-cy/order';
import { formatPriceCent } from '@/utils/formatter';

defineOptions({ name: 'DyjOrderList' });
const orderAmounts = ref(0),
  totalOrders= ref(0);
const { state, tableState, tableEvent, ...methods } = useTableList({
  getList: async (params: any) => {
    const res = await getList(params);
    orderAmounts.value = res.data?.order_amounts ? formatPriceCent(res.data?.order_amounts) : 0;
    totalOrders.value = res.data?.total_orders || 0;
    return res;
  }
});

const drawerRef = ref();

// 创建订单
const handleOpenDrawer = () => {
  if (hasPermission(AuthCode.CY_CREATE_ORDER)) {
    let row = {
      mobile: '',
      total_fee: '',
      complete_time: '',
      order_type: 1,
      // level: 20,
      month_type: 1,
      remark: ''
    };
    drawerRef.value?.show(0, row);
  }
};

// 编辑
const onClickEdit = (row: any) => {
  drawerRef.value?.show(1, row);
};

/** 处理订单退款 */
const handleRefund = async (row: any) => {
  if (hasPermission(AuthCode.CY_ORDER_REFUND)) {
    const { order_no, id } = row;
    try {
      const isPass = await baseConfirm({
        title: '订单退款',
        message: h('div', null, [h('span', null, '确认将'), h('span', { style: { color: 'blue' } }, order_no), h('span', null, '，状态修改为已退款吗？')])
      });
      if (isPass) {
        const res = await refundOrder(id);
        if (!res.err) {
          ElMessage.success('修改订单状态成功');
          methods.onSearch();
        }
      }
    } catch (e) {
      console.error(e);
    }
  }
};

/** 保存后的回调 */
const onAfterSubmit = () => {
  methods.onSearch();
};
</script>
<style lang="scss" scope>
.tool-right {
  display: flex;
  font-size: 14px;

  .right-desc {
    margin-left: 10px;

    span {
      padding-left: 5px;
      color: #666;
    }
  }
}
</style>
